from lxml import etree
from urllib.parse import (urljoin, quote)
import requests, base64
from settings.settings import (BASE_URL, HEADERS, get_access_token)

session = requests.Session()


def get_name(file_path):
    request_url = 'https://aip.baidubce.com/rest/2.0/image-classify/v2/dish'

    f = open(file_path, 'rb')
    img = base64.b64encode(f.read())

    params = {
        "image": img,
        "top_num": 5
    }

    request_url = request_url + "?access_token=" + get_access_token()
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    print(">>>>>>>>>>>>>>>>>>", response.json())
    df = response.json()['result'][0]["name"]

    print("这道菜的名字是：" + df)
    return df


def getData(name):
    url = f"https://www.xinshipu.com/doSearch.html?q={quote(name)}"

    response = session.get(url, headers=HEADERS, allow_redirects=False)
    next_url = urljoin(BASE_URL, response.headers['location'])
    response = session.get(next_url, headers=HEADERS)
    soup = etree.HTML(response.text)

    div_list = soup.xpath('//ul[@class="search-list mt-12 clearfix"]/li')
    for div in div_list:
        try:
            href = div.xpath('a/@href')[0]
            innerUrl = urljoin(BASE_URL, href)
            title = div.xpath('a/div/div/p/text()')[0]
            ret_list = []

            # 做法
            response = session.get(innerUrl, headers=HEADERS)
            zuofa_soup = etree.HTML(response.text)
            zuofa_list = zuofa_soup.xpath('//div[@class="swipeboxEx mlr1 bbm"]//text()')[:-2]
            for zuofa in zuofa_list:
                result = zuofa.replace("\r", "").replace("\n", "").strip()
                if result != "":
                    ret_list.append(result)

            # 获取材料
            cailiao_list = zuofa_soup.xpath('//p[@class="ptm12 mlr1 btm"]//text()')
            cailiao_str = "".join(cailiao_list)
            print(cailiao_str)

            return title, "\n".join(ret_list), cailiao_str
            break

        except:
            print("出错啦")


if __name__ == '__main__':
    print(getData("可乐鸡翅"))
